/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.grant;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.rbac.exception.PermissionException;
import com.je.rbac.service.grant.RbacGrantService;
import com.je.rbac.service.grant.RbacGrantTreeService;
import com.je.rbac.service.permission.GrantMethodEnum;
import com.je.rbac.service.permission.GrantTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/je/rbac/cloud/grant")
public class RbacGrantController extends AbstractPlatformController {

    @Autowired
    private RbacGrantService rbacGrantService;
    @Autowired
    private RbacGrantTreeService rbacGrantTreeService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;

    /**
     * 加载账户
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/loadAccount"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadAccount(HttpServletRequest request) {
        String type = getStringParameter(request, "type");
        String ids = getStringParameter(request, "ids");
        String start = getStringParameter(request, "start");
        String limit = getStringParameter(request, "limit");
        String orgId = getStringParameter(request, "orgId");
        String search = getStringParameter(request, "search");
        String logType = getStringParameter(request, "loadTYpe");

        if (Strings.isNullOrEmpty(type) || Strings.isNullOrEmpty(ids)) {
            return BaseRespResult.errorResult("请选择要查询的类型或标识！");
        }

        if (Strings.isNullOrEmpty(start)) {
            start = "0";
        }

        if (Strings.isNullOrEmpty(limit)) {
            limit = "30";
        }

        ConditionsWrapper wrapper = ConditionsWrapper.builder();
        if ("role".equals(type)) {
            wrapper.table("JE_RBAC_VACCOUNTROLE");
            wrapper.in("ACCOUNTROLE_ROLE_ID", Splitter.on(",").splitToList(ids));
            getWrapperSerch(orgId, search, wrapper);
            if (!Strings.isNullOrEmpty(logType) && "develop".equals(logType)) {
                wrapper.orderByDesc("ACCOUNTROLE_SY_CREATETIME");
            } else {
                wrapper.orderByAsc("ORG_SY_ORDERINDEX", "AR_SY_ORDERINDEX", "ACCOUNTROLE_SY_CREATETIME");
            }
        } else if ("department".equals(type)) {
            wrapper.table("JE_RBAC_VACCOUNTDEPT");
            wrapper.in("ACCOUNTDEPT_DEPT_ID", Splitter.on(",").splitToList(ids));
            getWrapperSerch(orgId, search, wrapper);
            wrapper.orderByAsc("SY_ORDERINDEX");
        } else if ("org".equals(type)) {
            wrapper.table("JE_RBAC_VACCOUNTDEPT");
            wrapper.in("SY_ORG_ID", Splitter.on(",").splitToList(ids));
            getWrapperSerch(orgId, search, wrapper);
            wrapper.orderByDesc("SY_CREATETIME");
        } else {
            return BaseRespResult.errorResult("不支持的参数列表！");
        }
        Page page = new Page(Integer.valueOf(start), Integer.valueOf(limit));
        List<Map<String, Object>> accountList = metaService.selectSql(page, wrapper);
        page.setRecords(accountList);
        return page == null ? BaseRespResult.successResultPage(Lists.newArrayList(), 0L) : BaseRespResult.successResultPage(page.getRecords(), (long) page.getTotal());
    }

    public void getWrapperSerch(String orgId, String search, ConditionsWrapper wrapper) {
        if (!Strings.isNullOrEmpty(orgId)) {
            wrapper.eq("SY_ORG_ID", orgId);
        }
        if (!Strings.isNullOrEmpty(search)) {
            wrapper.and(searchWrapper -> {
                searchWrapper.like("ACCOUNT_NAME", search);
            });
        }
    }

    //    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/loadDevelopTab"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadDevelopTab() {
        String mangerId = systemSettingRpcService.findSettingValue("JE_SYS_ADMIN");
        if (Strings.isNullOrEmpty(mangerId)) {
            return BaseRespResult.successResult(false);
        }

        List<DynaBean> managerBeanList = metaService.select("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().in("JE_RBAC_ACCOUNTDEPT_ID", Splitter.on(",").splitToList(mangerId)));
        if (managerBeanList == null || managerBeanList.isEmpty()) {
            return BaseRespResult.successResult(false);
        }

        if (Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountId())) {
            return BaseRespResult.successResult(false);
        }

        for (DynaBean eachBean : managerBeanList) {
            if (eachBean.getStr("ACCOUNTDEPT_ACCOUNT_ID").equals(SecurityUserHolder.getCurrentAccountId())) {
                return BaseRespResult.successResult(true);
            }
        }

        return BaseRespResult.successResult(false);
    }

    /**
     * 加载顶级菜单
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/loadTopMenus"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadTopMenus(HttpServletRequest request) {
        String type = getStringParameter(request, "type");
        String ids = getStringParameter(request, "ids");
        String dev = getStringParameter(request, "dev");
        return BaseRespResult.successResult(rbacGrantService.loadTopMenus(GrantMethodEnum.getGrantType(type), ids, "1".equals(dev) ? true : false));
    }

    /**
     * 加载导入的功能
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/loadImportFuncs"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadImportFuncs(HttpServletRequest request) {
        return BaseRespResult.successResult(rbacGrantService.loadImportFuncs());
    }

    /**
     * 导入功能授权
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/importFuncs"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult importFuncs(HttpServletRequest request) {
        String strData = getStringParameter(request, "strData");
        if (Strings.isNullOrEmpty(strData)) {
            return BaseRespResult.errorResult("请选择要导入的功能！");
        }
        rbacGrantService.importFuncs(strData);
        return BaseRespResult.successResult("导入成功！");
    }

    /**
     * 删除功能授权
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/removeFuncs"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult removeFuncs(HttpServletRequest request) {
        String type = getStringParameter(request, "type");
        String targetIds = getStringParameter(request, "targetIds");
        String funcIds = getStringParameter(request, "funcIds");
        if (Strings.isNullOrEmpty(type)) {
            return BaseRespResult.errorResult("请选择授权类型！");
        }
        if (Strings.isNullOrEmpty(targetIds)) {
            return BaseRespResult.errorResult("请选择权限集合！");
        }
        if (Strings.isNullOrEmpty(funcIds)) {
            return BaseRespResult.errorResult("请选择要删除的记录！");
        }
        rbacGrantService.removeFuncs(type, targetIds, funcIds);
        return BaseRespResult.successResult("删除成功！");
    }

    /**
     * 加载账号权限树
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/loadAccountPermissionTree"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadAccountPermissionTree(HttpServletRequest request) {
        String accountId = getStringParameter(request, "accountId");
        if (Strings.isNullOrEmpty(accountId)) {
            return BaseRespResult.errorResult("请选择要查看的账户！");
        }
        JSONTreeNode root = rbacGrantTreeService.loadAccountMenuPermissions(accountId);
        return BaseRespResult.successResult(root);
    }

    /**
     * 加载权限树
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/loadPermissionTree"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadPermissionTree(HttpServletRequest request) {
        String type = getStringParameter(request, "type");
        String ids = getStringParameter(request, "ids");
        String topMenuId = getStringParameter(request, "topMenuId");

        if (Strings.isNullOrEmpty(type)) {
            return BaseRespResult.errorResult("请选择角色或部门或机构！");
        }

        if (Strings.isNullOrEmpty(ids)) {
            return BaseRespResult.errorResult("请选择相关数据！");
        }
        if (Strings.isNullOrEmpty(topMenuId)) {
            return BaseRespResult.errorResult("请选择菜单模块！");
        }
        JSONTreeNode root = rbacGrantTreeService.loadMenuPermissions(type, ids, topMenuId);
        return BaseRespResult.successResult(root);
    }

    /**
     * 加载功能权限
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/loadFuncPermissionTree"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult loadFuncPermissionTree(HttpServletRequest request) {
        String type = getStringParameter(request, "type");
        String ids = getStringParameter(request, "ids");
        String funcCodes = getStringParameter(request, "funcCodes");
        if (Strings.isNullOrEmpty(type)) {
            return BaseRespResult.errorResult("请选择加载的权限类型！");
        }
        if (Strings.isNullOrEmpty(ids)) {
            return BaseRespResult.errorResult("请选择要加载的权限对象！");
        }
        if (Strings.isNullOrEmpty(funcCodes)) {
            return BaseRespResult.errorResult("请选择功能！");
        }
        JSONTreeNode rootNode = rbacGrantTreeService.loadFuncPermissions(type, ids, funcCodes.split(","));
        return BaseRespResult.successResult(rootNode);
    }

    /**
     * 自己控制权限（角色）
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/selfControlPermByRole"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult selfControlPermByRole(HttpServletRequest request) {
        String id = getStringParameter(request, "id");
        String strData = getStringParameter(request, "strData");
        String type = getStringParameter(request, "type");

        if (Strings.isNullOrEmpty(type)) {
            return BaseRespResult.errorResult("请选择取消类型！");
        }

        if (Strings.isNullOrEmpty(id)) {
            return BaseRespResult.errorResult("请选择操作对象！");
        }

        if (Strings.isNullOrEmpty(strData)) {
            return BaseRespResult.errorResult("请选择要不受控的对象！");
        }

        try {
            rbacGrantService.selfControlPerm(GrantTypeEnum.getGrantType(type), GrantMethodEnum.ROLE, id, strData);
            return BaseRespResult.successResult("操作成功！");
        } catch (PermissionException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    /**
     * 自己控制权限(部门)
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/selfControlPermByDepartment"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult selfControlPermByDepartment(HttpServletRequest request) {
        String id = getStringParameter(request, "id");
        String strData = getStringParameter(request, "strData");
        String type = getStringParameter(request, "type");

        if (Strings.isNullOrEmpty(type)) {
            return BaseRespResult.errorResult("请选择取消类型！");
        }

        if (Strings.isNullOrEmpty(id)) {
            return BaseRespResult.errorResult("请选择操作对象！");
        }

        if (Strings.isNullOrEmpty(strData)) {
            return BaseRespResult.errorResult("请选择要不受控的对象！");
        }

        try {
            rbacGrantService.selfControlPerm(GrantTypeEnum.getGrantType(type), GrantMethodEnum.DEPARTMENT, id, strData);
            return BaseRespResult.successResult("操作成功！");
        } catch (PermissionException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    /**
     * 恢复自己控制权限，至继承原权限
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/cancelSelfControlPermByRole"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult cancelSelfControlPermByRole(HttpServletRequest request) {
        String id = getStringParameter(request, "id");
        String strData = getStringParameter(request, "strData");
        String type = getStringParameter(request, "type");

        if (Strings.isNullOrEmpty(type)) {
            return BaseRespResult.errorResult("请选择取消类型！");
        }

        if (Strings.isNullOrEmpty(id)) {
            return BaseRespResult.errorResult("请选择操作对象！");
        }

        if (Strings.isNullOrEmpty(strData)) {
            return BaseRespResult.errorResult("请选择要不受控的对象！");
        }

        try {
            rbacGrantService.cancelSelfControlPerm(GrantTypeEnum.getGrantType(type), GrantMethodEnum.ROLE, id, strData);
            return BaseRespResult.successResult("操作成功！");
        } catch (PermissionException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    /**
     * 恢复自己控制权限，至继承原权限
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/cancelSelfControlPermByDepartment"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult cancelSelfControlPermByDepartment(HttpServletRequest request) {
        String id = getStringParameter(request, "id");
        String strData = getStringParameter(request, "strData");
        String type = getStringParameter(request, "type");

        if (Strings.isNullOrEmpty(type)) {
            return BaseRespResult.errorResult("请选择取消类型！");
        }

        if (Strings.isNullOrEmpty(id)) {
            return BaseRespResult.errorResult("请选择操作对象！");
        }

        if (Strings.isNullOrEmpty(strData)) {
            return BaseRespResult.errorResult("请选择要不受控的对象！");
        }

        try {
            rbacGrantService.cancelSelfControlPerm(GrantTypeEnum.getGrantType(type), GrantMethodEnum.DEPARTMENT, id, strData);
            return BaseRespResult.successResult("操作成功！");
        } catch (PermissionException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }
}
